package com.nx.platform.es.biz.query.search.handler;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.common.utils.MoreSplitters;
import com.nx.platform.es.biz.query.search.SearchRequestContext;
import com.nx.platform.es.common.utils.MoreFunctions;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchType;

import java.util.List;
import java.util.Set;

/**
 * @author
 * @since 2016年10月15日
 */
public enum SearchIndexHandler implements SearchRequestHandler {

    INSTANCE;

    @Override
    public void handle(SearchRequestContext context) {
        StringBuilder sb = context.getTrace();
        sb.append("&_entry=").append(context.getEntry());
        SearchRequest request = context.getRequest();
        request.indices(context.getIndex()).types(context.getType());
        request.searchType(SearchType.QUERY_THEN_FETCH);
        if (context.isFetchFields() && ArrayUtils.isNotEmpty(context.getFetch())) {
            Table<String, StatementOperator, List<String>> queryTable = context.getQueryTable();
            List<String> fetchStrs = queryTable.get("fetch", StatementOperator.EQUAL);
            if (CollectionUtils.isNotEmpty(fetchStrs)) {
                Set<String> fetchSet = MoreFunctions.toStringSet(fetchStrs.get(0), MoreSplitters.COMMA);
                List<String> fetchs = Lists.newLinkedList();
                for (String fetch : context.getFetch()) {
                    if (fetchSet.contains(fetch)) {
                        fetchs.add(fetch);
                    }
                }
                if (!fetchs.isEmpty()) {
                    String[] array = fetchs.toArray(new String[fetchs.size()]);
                    context.setFetch(array);
                    request.source().storedFields(fetchs);
                    sb.append("&_fields=").append(Joiner.on(',').join(fetchs));
                } else {
                    context.setFetch(null);
                }
            } else {
                request.source().storedField(context.getFetch()[0]);
                sb.append("&_fields=").append(context.getFetch()[0]);
            }
        }
        request.source().fetchSource(context.isFetchSource());
        if (context.isFetchSource()) {
            sb.append("&_source=").append(1);
        }
        if (context.isExplain()) {
            request.source().explain(true);
            sb.append("&_explain=").append(1);
        }
    }

}
